package org.spiderflow.common;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileWriter;

/**
 * file工具类
 *
 */
public class MyFileUtils {


    private static final Logger logger = LoggerFactory.getLogger(MyFileUtils.class);


    public static final String fileThreadPoolExecutorName = "fileThreadPoolExecutor";

    /**
     * 异步追加信息到文件末尾
     *
     * @param msg
     * @param fileName
     * @throws Exception
     */
    public static void addMsgToEnd(String msg, String fileName) throws Exception {
        synchronized (MyFileUtils.class) {//类级别锁
            File file = new File(fileName);
            if (!file.exists()) {
                try {
                    // 父文件夹是否存在
                    File fileParent = file.getParentFile();
                    if (!fileParent.exists()) {
                        fileParent.mkdirs();
                    }
                    file.createNewFile();
                } catch (Exception ex) {
                    logger.error("文件创建失败，请检查路径" + fileName + "是否合法以及读写权限");
                    return;
                }
            }
            FileWriter fileWritter = null;//todo-nicky 是否线程安全
            try {
                //使用true，即进行append file
                fileWritter = new FileWriter(file, true);
                fileWritter.write(msg);
                fileWritter.flush();
            } catch (Exception ex) {
                logger.error("fileName: " + fileName + ", msg: " + msg + "ex: " + ex.getMessage());
            } finally {
                if (fileWritter != null) {
                    try {
                        fileWritter.close();
                    } catch (Exception ex) {
                        logger.error("fileName: " + fileName + ", msg: " + msg + "ex: " + ex.getMessage());
                    }
                }
            }
        }
    }
}
